<template>
	<div class="wrapper">
		<!-- header部分 -->
		<header>
			<p>地址管理</p>
		</header>

		<!-- 地址列表部分 -->
		<ul class="addresslist">
			<li v-for="item in deliveryAddressArr" :key="item.id">
				<div class="addresslist-left" @click="setDeliveryAddress(item)">
					<h3>{{item.contactName}}{{item.contactSex | sexFilter}} {{item.contactTel}}</h3>
					<p>{{item.address}}</p>
				</div>
				<div class="addresslist-right">
					<i class="fa fa-edit" @click="editUserAddress(item.id)"></i>
					<i class="fa fa-remove" @click="removeUserAddress(item.id)"></i>
				</div>
			</li>
		</ul>

		<!-- 新增地址部分 -->
		<div class="addbtn" @click="toAddUserAddress">
			<i class="fa fa-plus-circle"></i>
			<p>新增收货地址</p>
		</div>

		<!-- 底部菜单部分 -->
		<Footer></Footer>
	</div>
</template>

<script>
	import Footer from '../components/Footer.vue';

	export default {
		name: 'UserAddress',
		data() {
			return {
				businessId: this.$route.query.businessId,
				// 接收从订单页面传递的参数
				orderItems: null,
				totalPrice: null,
				deliveryPrice: null,
				deliveryAddressArr: []
			}
		},
		created() {
			// 获取从订单页面传递的参数
			const {
				orderItems,
				totalPrice,
				deliveryPrice
			} = this.$route.query;
			if (orderItems) this.orderItems = orderItems;
			if (totalPrice) this.totalPrice = totalPrice;
			if (deliveryPrice) this.deliveryPrice = deliveryPrice;

			this.listDeliveryAddressByUserId();
		},
		components: {
			Footer
		},
		filters: {
			sexFilter(value) {
				return value == 1 ? '先生' : '女士';
			}
		},
		methods: {
			// 获取地址列表（GET /api/addresses）
			listDeliveryAddressByUserId() {
				const token = localStorage.getItem('id_token');
				if (!token) {
					this.$router.push('/login');
					return;
				}
				this.$axios.get('addresses', {
					headers: {
						'Authorization': `Bearer ${token}`
					}
				}).then(response => {
					const result = response.data;
					if (result.success && result.code === 200) {
						this.deliveryAddressArr = result.data;
					} else {
						alert('获取地址列表失败：' + (result.message || '未知错误'));
					}
				}).catch(error => {
					console.error('获取地址列表出错：', error);
				});
			},
			// 选择地址后返回订单页，带回所有必要参数
			setDeliveryAddress(item) {
				this.$router.push({
					path: '/orders',
					query: {
						businessId: this.businessId,
						selectedAddressId: item.id.toString()
					}
				});
			},
			toAddUserAddress() {
				this.$router.push({
					path: '/addUserAddress',
					query: {
						businessId: this.businessId
					}
				});
			},
			editUserAddress(daId) {
				this.$router.push({
					path: '/editUserAddress',
					query: {
						businessId: this.businessId,
						daId: daId
					}
				});
			},
			// 删除地址（DELETE /api/addresses/{id}）- 修复API路径
			removeUserAddress(daId) {
				if (!confirm('确认要删除此送货地址吗？')) return;

				const token = localStorage.getItem('id_token');
				this.$axios.delete(`addresses/${daId}`, { // 修复API路径与获取地址时一致
					headers: {
						'Authorization': `Bearer ${token}`
					}
				}).then(response => {
					const result = response.data;
					if (result.success && result.code === 200) {
						this.listDeliveryAddressByUserId(); // 重新加载列表
					} else {
						alert('删除失败：' + (result.message || '未知错误'));
					}
				}).catch(error => {
					console.error('删除地址出错：', error);
					alert('删除地址时发生错误，请稍后重试');
				});
			}
		}
	}
</script>

<style scoped>
	/*************** 总容器 ***************/
	.wrapper {
		width: 100%;
		min-height: 100vh;
		background-color: #F5F5F5;
	}

	/*************** header ***************/
	.wrapper header {
		width: 100%;
		height: 12vw;
		background-color: #0097FF;
		display: flex;
		justify-content: center;
		/* 优化居中方式 */
		align-items: center;
		color: #fff;
		font-size: 4.8vw;
		position: fixed;
		left: 0;
		top: 0;
		z-index: 1000;
	}

	/*************** addresslist ***************/
	.wrapper .addresslist {
		width: 100%;
		margin-top: 12vw;
		background-color: #fff;
		padding-bottom: 20vw;
		/* 避免被底部菜单遮挡 */
	}

	.wrapper .addresslist li {
		width: 100%;
		box-sizing: border-box;
		border-bottom: solid 1px #DDD;
		padding: 3vw;
		display: flex;
	}

	.wrapper .addresslist li .addresslist-left {
		flex: 5;
		user-select: none;
		cursor: pointer;
		-webkit-tap-highlight-color: rgba(0, 0, 0, 0.1);
		transition: background-color 0.2s;
	}

	.wrapper .addresslist li .addresslist-left h3 {
		font-size: 4.6vw;
		font-weight: 300;
		color: #666;
		margin-bottom: 1vw;
	}

	.wrapper .addresslist li .addresslist-left p {
		font-size: 4vw;
		color: #666;
	}

	.wrapper .addresslist li .addresslist-right {
		flex: 1;
		font-size: 5.6vw;
		color: #999;
		cursor: pointer;
		display: flex;
		justify-content: space-around;
		align-items: center;
	}

	/* 图标点击反馈 */
	.wrapper .addresslist li .addresslist-right i {
		-webkit-tap-highlight-color: rgba(0, 0, 0, 0.1);
		transition: color 0.2s;
	}

	.wrapper .addresslist li .addresslist-right i:active {
		color: #0097FF;
	}

	/*************** 新增地址部分 ***************/
	.wrapper .addbtn {
		width: 100%;
		height: 14vw;
		border-top: solid 1px #DDD;
		border-bottom: solid 1px #DDD;
		background-color: #fff;
		margin-top: 4vw;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 4.5vw;
		color: #0097FF;
		user-select: none;
		cursor: pointer;
		-webkit-tap-highlight-color: rgba(0, 0, 0, 0.1);
		transition: background-color 0.2s;
	}

	.wrapper .addbtn p {
		margin-left: 2vw;
	}

	/* 新增按钮点击反馈 */
	.wrapper .addbtn:active {
		opacity: 0.8;
	}
</style>